﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using CMS.Common.Helpers;
using CMS.Common.Json;
using CMS.Common.Mvc;
using CMS.Service.EnumHelper;
using CMS.Service.Repository;
using CMSApplication.Areas.Administration.Models;

namespace CMSApplication.Areas.Administration.Controllers
{
    public class ManagementController : UTController
    {
        private WorkRepository wrk_srv = new WorkRepository();
        private UserRepositry user_srv = new UserRepositry();
        private CustomerRepository customer_srv = new CustomerRepository();

        //
        // GET: /Administration/Management/
        private EncryptAndDecrypt encrypt = new EncryptAndDecrypt();
         [Authorize(Roles = "Administrator,User")]
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult Logon()
        {
            return View(); 
        }
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                model.Password = encrypt.Encrypt(model.Password, "Click4Restaurants", true);
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Management", new { area="Administration"});
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
         [Authorize(Roles = "Administrator,Manager")]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Management", new { area = "Administration" });
        }

        #region Images

        public string UploadImage(HttpPostedFileBase file)
        {
            string basePath = "~/Content/img";
            FileHelper fileHelper = new FileHelper(basePath);
            string fileName = fileHelper.SaveFile(null, file.FileName, file.InputStream);
            string filePathStr = Url.Content(basePath) + @"/" + fileName;
            return filePathStr;
        }

        [HttpPost]
        public ActionResult UploadImageStr(string qqfile)
        {
            string basePath = "~/Content/File/ImagesUpload";
            string[] fileNameArray = qqfile.Split(new char[] { '.' });
            if (fileNameArray.Length == 1)
            {
                return JsonError("Error!");
            }
            FileHelper fileHelper = new FileHelper(basePath);
            string fileName = fileHelper.SaveFile(null, fileNameArray[1], Request.InputStream);
            string filePathStr = Url.Content(basePath) + @"/" + fileName;

            return Json(new { success = true,  filePath = fileName });
        }

        [HttpPost]
        public ActionResult UploadImageStrFIle(string qqfile)
        {
            string basePath = "~/Content/File/FileUpload";
            string[] fileNameArray = qqfile.Split(new char[] { '.' });
            if (fileNameArray.Length == 1)
            {
                return JsonError("Error!");
            }
            FileHelper fileHelper = new FileHelper(basePath);
            string fileName = fileHelper.SaveFile(null, fileNameArray[1], Request.InputStream);
            string filePathStr = Url.Content(basePath) + @"/" + fileName;
            return Json(new { success = true, filePath = fileName });
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadImage(HttpPostedFileBase upload, string CKEditorFuncNum,
                                      string CKEditor, string langCode)
        {
            string url = string.Empty; // url to return
            string message = string.Empty; // message to display (optional)

            // here logic to upload image
            // and get file path of the image

            // path of the image
            string path = UploadImage(upload);

            // will create http://localhost:1457/Content/Images/my_uploaded_image.jpg

            url = Request.Url.GetLeftPart(UriPartial.Authority) + path;

            // passing message success/failure
            message = "Upload image success.";

            // since it is an ajax request it requires this string
            string output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum + ", \"" + url + "\", \"" + message + "\");</script></body></html>";
            return Content(output);
        }

        #endregion

        #region Site Security
        /// <summary>
        /// Take down the site 
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public string SiteDown(string password)
        {
            return CMS.Common.Security.ABSecurity.TakeDown(encrypt.Encrypt(password, "absoft.vn", true)).ToString();
        }

        /// <summary>
        /// Site up to normal state
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public string SiteUp(string password)
        {
            return CMS.Common.Security.ABSecurity.TakeUp(encrypt.Encrypt(password, "absoft.vn", true)).ToString();
        }
        #endregion

        [Authorize(Roles = "Administrator,Manager")]
        public ActionResult Wrk_NextTimes_List()
        {
            List<WorkModel> res = new List<WorkModel>();

            var status_lst = EnumHelper.Get_Enum_Wrk_Status();
            var customer_lst = customer_srv.List();
            var staff_lst = user_srv.List();

            var c = wrk_srv.List(null, 0, 0, DateTime.MinValue, DateTime.MinValue, (int)Enum_Wrk_Status.NextTimes, 0);
            foreach (var item in c)
            {
                WorkModel ml = new WorkModel();
                WorkModel.MapFrom(item, ref  ml);

                var status = status_lst.Where(x => x.Key == ml.Status).FirstOrDefault();
                var customer = customer_lst.Where(x => x.Id == ml.AssignCustomer).FirstOrDefault();
                var staff = staff_lst.Where(x => x.Id == ml.AssignStaff).FirstOrDefault();

                if (status_lst.Count(x => x.Key == ml.Status) > 0) ml.StatusName = status_lst.Where(x => x.Key == ml.Status).First().Value;
                if (customer != null)
                {
                    ml.CustomerName = string.Format("{0} - {1}", customer.Id.ToString().PadLeft(4, '0'), customer.Name);
                    ml.CustomerAddr = customer.Addr;
                    ml.CustomerPhone = customer.Phone;
                }
                if (staff != null) ml.StaffName = string.Format("{0} - {1}", staff.Id.ToString().PadLeft(4, '0'), staff.FullName);

                res.Add(ml);
            }

            return PartialView("_Wrk_NextTimes_List", res);
        }

        public ActionResult Wrk_Chart_Revenue(DateTime req)
        {
            List<KeyValuePair<int, double>> res = new List<KeyValuePair<int, double>>();

            DateTime assign_on_from = new DateTime(req.Year, req.Month, 1);
            DateTime assign_on_to = new DateTime(req.Year, req.Month, 1).AddMonths(1).Subtract(TimeSpan.FromTicks(1));
            var c = wrk_srv.List(null, 0, 0, assign_on_from, assign_on_to, (int)Enum_Wrk_Status.Complete, 0);
            
            DateTime assign_on_sta = assign_on_from;
            DateTime assign_on_end = assign_on_sta.AddDays(1).Subtract(TimeSpan.FromTicks(1));
            do
            {
                var t = c.Where(x => x.AssignOn >= assign_on_sta && x.AssignOn <= assign_on_end);
                res.Add(new KeyValuePair<int, double>(assign_on_sta.Day, t.Sum(x => x.Collected - x.Cost).Value));

                assign_on_sta = assign_on_sta.AddDays(1);
                assign_on_end = assign_on_end.AddDays(1);
            } while (assign_on_end <= assign_on_to);

            return Json(res, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Wrk_Chart_NumCus(DateTime req)
        {
            List<KeyValuePair<int, double>> res = new List<KeyValuePair<int, double>>();

            DateTime assign_on_from = new DateTime(req.Year, req.Month, 1);
            DateTime assign_on_to = new DateTime(req.Year, req.Month, 1).AddMonths(1).Subtract(TimeSpan.FromTicks(1));
            var c = wrk_srv.List(null, 0, 0, assign_on_from, assign_on_to, (int)Enum_Wrk_Status.Complete, 0);

            DateTime assign_on_sta = assign_on_from;
            DateTime assign_on_end = assign_on_sta.AddDays(1).Subtract(TimeSpan.FromTicks(1));
            do
            {
                var t = c.Where(x => x.AssignOn >= assign_on_sta && x.AssignOn <= assign_on_end);
                res.Add(new KeyValuePair<int, double>(assign_on_sta.Day, t.Count(x => x.AssignCustomer > 0)));

                assign_on_sta = assign_on_sta.AddDays(1);
                assign_on_end = assign_on_end.AddDays(1);
            } while (assign_on_end <= assign_on_to);

            return Json(res, JsonRequestBehavior.AllowGet);
        }
    }
}
